package com.rzico.sbl.ui.report.invite

import android.widget.EditText
import android.widget.ImageView
import com.lzg.extend.jackson.JsonUtil
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityReportInviteDetailBinding
import com.rzico.sbl.model.DispatchBucket
import com.rzico.sbl.model.DispatchRotten
import com.rzico.sbl.viewmodel.ReportInviteViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.startRotateAnimator
import com.xinnuo.common.view.FullyLinearLayoutManager
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common.helper.intValue
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.subscribeBySuccess
import com.xinnuo.slimadapter.SlimAdapter
import net.cachapa.expandablelayout.ExpandableLayout
import org.json.JSONArray
import org.json.JSONObject

class ReportInviteDetailActivity : BaseActivity(R.layout.activity_report_invite_detail) {

    private val mBinding by lazy { ActivityReportInviteDetailBinding.bind(getRootView()) }

    private lateinit var mBarrelAdapter: SlimAdapter
    private lateinit var mRottenAdapter: SlimAdapter
    private var mShopId = ""
    private var mInviteId = ""
    private val mEditList = arrayListOf<DispatchBucket>()
    private val mRottenList = arrayListOf<DispatchRotten>()

    override fun getViewModel() = get<ReportInviteViewModel>()

    override fun initData() {
        initTitle(title = "入空桶详情")

        initBarrelLayout()
        initRottenLayout()

        getInviteDetail()
    }

    private fun initBarrelLayout() {
        mBinding
            .barrelList
            .apply {
                isNestedScrollingEnabled = false
                layoutManager = FullyLinearLayoutManager(baseContext)

                addItemDecoration(SpaceTBDecoration(hasHeader = false, hasFooter = false))

                mBarrelAdapter = SlimAdapter.creator()
                    .register<DispatchBucket>(R.layout.item_report_invite_bucket) { jector, bean, _ ->
                        jector.apply {
                            gone(R.id.item_bucket_del)
                            text(R.id.item_bucket_barrel, bean.name) //品牌
                            text(R.id.item_bucket_change, bean.transQuantity.orEmpty("0")) //兑换桶
                            text(R.id.item_bucket_total, bean.returnQuantity.orEmpty("0")) //总入库

                            // 入库
                            with<EditText>(R.id.item_bucket_in) {
                                it.isEnabled = false
                                it.setText(bean.memo2.orEmpty("0"))
                            }

                            // 外品牌1:1
                            with<EditText>(R.id.item_bucket_one) {
                                it.isEnabled = false
                                it.setText(bean.percent1.orEmpty("0"))
                            }

                            // 外品牌2:1
                            with<EditText>(R.id.item_bucket_two) {
                                it.isEnabled = false
                                it.setText(bean.percent2.orEmpty("0"))
                            }

                            // 外品牌3:1
                            with<EditText>(R.id.item_bucket_three) {
                                it.isEnabled = false
                                it.setText(bean.percent3.orEmpty("0"))
                            }

                            // 外品牌补差价
                            with<EditText>(R.id.item_bucket_fill) {
                                it.isEnabled = false
                                it.setText(bean.percent4.orEmpty("0"))
                            }

                            // 补差价金额
                            with<EditText>(R.id.item_bucket_money) {
                                it.isEnabled = false
                                it.setText(bean.differPrice.formatDecimal())
                            }

                            clicked(R.id.item_bucket_change_ll) {
                                val expand = getView<ExpandableLayout>(R.id.item_bucket_expand)
                                val arrow = getView<ImageView>(R.id.item_bucket_change_arrow)

                                if (expand.isExpanded) {
                                    expand.collapse()
                                    arrow.startRotateAnimator(90f, 0f)
                                } else {
                                    expand.expand()
                                    arrow.startRotateAnimator(0f, 90f)
                                }
                            }
                        }
                    }
                    .attachTo(this)
            }
    }

    private fun initRottenLayout() {
        mBinding
            .rottenList
            .apply {
                isNestedScrollingEnabled = false
                layoutManager = FullyLinearLayoutManager(baseContext)

                addItemDecoration(SpaceTBDecoration(hasHeader = false, hasFooter = false))

                mRottenAdapter = SlimAdapter.creator()
                    .register<DispatchRotten>(R.layout.item_report_invite_rotten) { jector, bean, _ ->
                        jector.apply {
                            gone(R.id.item_rotten_del)
                            text(R.id.item_rotten_name, bean.name)
                            text(R.id.item_rotten_price, bean.price.formatDecimal())
                            text(R.id.item_rotten_amount, bean.subPrice.formatDecimal())

                            // 烂桶数量
                            with<EditText>(R.id.item_rotten_count) {
                                it.isEnabled = false
                                it.setText(bean.quantity.orEmpty("0"))
                            }
                        }
                    }
                    .attachTo(this)
            }
    }

    override fun initListener() {
        mBinding.apply {
            mShopId = intent.getExtra("shopId")
            mInviteId = intent.getExtra("inviteId")
            inviteTitle.text = intent.getExtra("shopName")
        }
    }

    /**
     * 入空桶详情
     */
    private fun getInviteDetail() {
        getViewModel()
            .inviteDetail(mInviteId)
            .bindLifeCycle(getLifecycleOwner())
            .subscribeBySuccess(
                event = getViewModel(),
                onSuccess = { result ->
                    val obj = JSONObject(result)

                    mShopId = obj.optNotNull("enterpriseId")
                    mInviteId = obj.optNotNull("id")

                    mBinding
                        .apply {
                            inviteTitle.text = obj.optNotNull("name")
                            inviteMemo.text = obj.optNotNull("memo")
                        }

                    /*-------- 空桶信息 --------*/
                    val objBarrel = obj.optJSONArray("creditBarrels") ?: JSONArray()
                    mEditList.clear()
                    mEditList.addItems(
                        JsonUtil.toList(
                            objBarrel.toString(),
                            DispatchBucket::class.java
                        )
                    )

                    // 计算入库数
                    mEditList.forEach {
                        val count =
                            (it.returnQuantity.intValue
                                    - it.transQuantity.intValue)

                        if (count > 0) it.memo2 = count.toString()
                    }

                    mBarrelAdapter.setDataList(mEditList)

                    /*-------- 烂桶信息 --------*/
                    val objRotten = obj.optJSONArray("creditSwaps") ?: JSONArray()
                    mRottenList.clear()
                    mRottenList.addItems(
                        JsonUtil.toList(
                            objRotten.toString(),
                            DispatchRotten::class.java
                        )
                    )
                    mRottenAdapter.setDataList(mRottenList)
                }
            )
    }

}